$(function(){
	var sorFlag=false;
	var fenFlag=false;
	requestSource();//渠道
	requestClassification();//分级
	requestSort();//分类*/
	requestPort(); 
	var detailId=queryString('updateId');
	var flowId=queryString('flowid');
	requestDetail(detailId);
	getInformationFlow(detailId);
	
	var checkFlag={sele:false,pes:false,sort:false};
	var file={};
	var information={};
	//返回
	$("#goback").click(function(){
		window.location.href="/yuxi/model/information/submittedInfo.jsp?menuId=2";
	})
	//文件上传按钮
	$("#fileUp").click(function(){
		
		$("#loading").hide();
		$("#loadOk").hide();
	})
	$("#fileUp").on("change","#upfile-haoping",function(){
		fileup();
	})
	//确认修改按钮
	$("#requestUpdate").click(function(){
		getInformation();

	})
	//修改模态框确认按钮
	$("#update").click(function(){
		requestUpdate();//调用修改数据方法
		$("#updateModal").modal('hide');
	})
	$(document).on('click','.glyphicon-remove',function(){
		$(this).parent().remove();
	});
	//所有数据，和上一层id
	var childer2=[];  
	var childer=[];  
	function xxx(object,className){
		var type="";
		var name="";
		var flag="";
		if(className=="#treeTable1")
		{
			type="checkbox";
			name="sourceCheck";
			flag="name";
		}
		else
		{
			type="radio";
			name="safePort";
			flag="portName";
		}
		var a=[];
		var flag=0;
			var html="";
		var flaga={};
		
		function treeMenu(a){
		    this.tree=a||[];
		    this.groups={};
		};
		treeMenu.prototype={
		    init:function(superId){
		  
		        this.group();
		        return this.getDom(this.groups[superId]);
		    },
		    group:function(){
		    
		        for(var i=0;i<this.tree.length;i++){
		            if(this.groups[this.tree[i].superId]){
		                this.groups[this.tree[i].superId].push(this.tree[i]);
		            }else{
		                this.groups[this.tree[i].superId]=[];
		                this.groups[this.tree[i].superId].push(this.tree[i]);
		            }
		        }

		    },

		    getDom:function(a){
		    	
		    	
		        if(!a){return ''}
		       flag=0;
		        var html="";
		    
		    	if(a[0].superId==0)
		    	{
		    			/*$scope.sorce=a;//第一层结构
		    			//console.log($scope.sorce);*/
		    			for(var i=0;i<a.length;i++)
		    			{
		    				
		    				if(className=="#treeTable2")
		    				{
		    					html='<tr isChange=false id="'+a[i].id+'"   hasChild="hasChild" data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].portName+'</td><td><input data-name='+a[i].portName+' data-id='+a[i].id+' type='+type+' name='+name+'></td></tr>\n';		
		    				}
		    				else
		    				{
		    					html='<tr isChange=false id="'+a[i].id+'"   hasChild="hasChild" data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].name+' data-id='+a[i].id+' type='+type+' name='+name+'></td></tr>\n';		

		    				}
		    				$(className).append(html);
		    				
		    			}
		    			
		    			flag=1;
		    	}
		    	////console.log("aa"+JSON.stringify(a));
		    	if(flag==0)
		    	{
		    			var length=a.length;
		    			var superid=0;
		    			for(var i=0;i<length;i++)
		    			{	
		    				superid=a[i].superId;
		    				if(isChilde(a[i].id,object))
		    				{ 
		    					
		    					if(className=="#treeTable2")
		    					{

		    					html+='<tr isChange=false id="'+a[i].id+'" hasChild="hasChild" pId="'+a[i].superId+'"   data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].portName+' data-id='+a[i].id+' type='+type+' name='+name+'></td> </tr>\n';		
		    					}
		    					else
		    					{
		    						html+='<tr isChange=false id="'+a[i].id+'" hasChild="hasChild" pId="'+a[i].superId+'"   data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].name+' data-id='+a[i].id+' type='+type+' name='+name+'></td> </tr>\n';		
		    					}

		    				}  
		    				else
		    				{  			
		    					if(className=="#treeTable2")
		    					{
		    							html+='<tr isChange=false id="'+a[i].id+'" pId="'+a[i].superId+'"   data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].portName+'</td><td><input data-name='+a[i].portName+' data-id='+a[i].id+' type='+type+' name='+name+'></td></tr>\n';		
		    				
		    					}
		    					else
		    					{
		    						html+='<tr isChange=false id="'+a[i].id+'" pId="'+a[i].superId+'"   data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].name+' data-id='+a[i].id+' type='+type+' name='+name+'></td></tr>\n';		
		    				
		    					}
		    				}
		    				
		    				
		    				    
		    			}
		    				if(className=="#treeTable1")
		    				{
		    					childer.push({superid:superid,html:html});
		    				}
		    				else
		    				{
		    					childer2.push({superid:superid,html:html});
		    				}

		    			
		    		
		    		
		    			
		    	}
		    	 
		        for(var i=0;i<a.length;i++)
		        {
		           this.getDom(this.groups[a[i].id]);

		        }

	        /*html+='</optgroup>\n';*/

	       /* $("#"+id).append(html);*/
	        return html;
	    }
	   

	}
 var html=new treeMenu(object).init(0);
option(className);
if(className=="#treeTable2")
	{
		fenFlag=true;
	}
	else
	{
		sorFlag=true;
	}
}
	
	




//判断是否有子节点
function isChilde(id,object)
{
	for(var i=0;i<object.length;i++)
	{
		if(object[i].superId==id)
		{
			return true;
		}
	}
	return false;
}
	function option(className)
	{			

			var option = {
	                theme:'vsStyle',
	              	expandLevel:1,
	                beforeExpand : function($treeTable, id) {

	            	var html="";

					
	                    //判断id是否已经有了孩子节点，如果有了就不再加载，这样就可以起到缓存的作用
	                    if ($('.' + id, $treeTable).length) { return; }
	            
	                   var index=$(className).find("tr").eq(id).attr("id");
	                   if(className=="#treeTable2")
		    			{
		                   for(var i=0;i<childer2.length;i++)
		                   {
		                   	if(id==childer2[i].superid)
		                   	{
		                   		html=childer2[i].html;
		                   	}
		                   }
		                 }
		                 else
		                 {
		                 	 for(var i=0;i<childer.length;i++)
		                   	{
		                   		if(id==childer[i].superid)
		                   		{
		                   			html=childer[i].html;
		                   		}
		                  	 }
		                 }
	                 
	                     $treeTable.addChilds(html);

	                     $("input[name='sourceCheck']").each(function(){
					
							for(var i=0;i<Allsourcename.length;i++){
								
								if($(this).attr("data-id")==Allsourcename[i]){
									
									$(this).attr("checked","checked");
									break;
								}
							}
							
						});
						$("input[name='safePort']").each(function(){

								if($(this).attr("data-id")==AllportName){
									
									$(this).attr("checked","checked");
									
							}
							
						})
					},
					 onSelect : function($treeTable, id) {
	                    window.console && console.log('onSelect:' + id);
	                    
	                }


		}	
	
		$(className).treeTable(option);
	}


var x=1;	//向后台请求渠道信息
function space(superid,object)
{

	if(superid==0)
	{

		return 0;
	}
	for(var i=0;i<object.length;i++)
	{
		if(object[i].id==superid)
		{
			
			x=space(object[i].superId,object);
			
		}
	}
	return x+1;

}
//向后台请求分口信息
function requestPort()
{	var url="getAllInformationPort.do";//分口地址
	var data={};
	var object={};
	data=YuXi.util.get(url,null,function(data){
		object=data.object;		
			xxx(object,"#treeTable2");
		
	},function(){});//请求数据
	
}

function requestSource()
{	


	var url="getAllInfomationSource.do";//渠道地址
	var data={};
	var object={};
	var superId1=[];//第一层id
	YuXi.util.get(url,"null",function(data){
		object=data.object;		 
	xxx(object,"#treeTable1");
	
		
	},function(){});//请求数据



}
	


//向后台请求分级信息
function requestClassification()
{	
	var url="getAllInformationClassification.do";//分级地址
	var data={};
	var object={};
	data=YuXi.util.get(url,"null",function(data){
		object=data.object;
		//用data循环添加分口信息
		for(var i=0;i<object.length;i++)
		{
			var html="<option  value="+object[i].id+" >"+object[i].name+"</option>";
			$(".pes").append(html);
		}
		checkFlag.pes=true;
	},function(){
		
	});//请求数据
	
}


//向后台请求分类信息
function requestSort()
{	//数据模拟

	
	
	var url="getAllInfomationSort.do";//分类地址
	var data={};
	var object={};
	data=YuXi.util.get(url,"null",function(data){
		object=data.object;
		//用data循环添加分类信息
		for(var i=0;i<object.length;i++)
		{
			var html="<option  value="+object[i].id+" >"+object[i].name+"</option>";
			$(".sort").append(html);
		}
		checkFlag.sort=true;
	},function(){
		
	});//请求数据
	
}


function getInformationFlow(id){
		var url="getInformationFlowByInfoId.do";
		var infoId={infoId:id};
		var object={};
		YuXi.util.get(url,infoId,function(data){
			if(data.status){
				object=data.object;
				var flow;
				
				for (var i = 0; i < object.length; i++) {
					if(object[i].flowId==3){
						flow="初审"
					}
					if(object[i].flowId==2){
						flow="初审"
					}
					if(object[i].flowId==4){
						flow="复核"
					}
					if(object[i].flowId==5){
						flow="审核"
					}
					var time = YuXi.getTime.get(object[i].createTime);
					
					if(object[i].remark==undefined){
						object[i].remark="";
					}
					var html = "<tr ><td style='border:none;'>" + object[i].userName + "</td>+" +
					
					"<td style='border:none;'>" +time  + "</td>" +
					"<td style='border:none;'>" + object[i].remark + "</td>" +
					
					"<td style='border:none;'>" +flow  + "</td>" +
 					"</tr>";
					$("#tbody").append(html);
				}
			}
		},function(){
			
		});
	}
//正则取链接传来的数据
function queryString(key)
{
    var regex_str = "^.+\\?.*?\\b"+ key +"=(.*?)(?:(?=&)|$|#)"
    var regex = new RegExp(regex_str,"i");
    var url = window.location.toString();
    if(regex.test(url)) return RegExp.$1;
    return undefined;
}






//根据id向后台请求数据详情
function requestDetail(id)
{	
	var url="getUserInformationById.do";//向后台请求数据id
	var object={}
	var sourceName; 
	var personId;
	var personName;
	var dataid={informationId:id};
	YuXi.util.get(url,dataid,function(data){
		object=data.object;
		sourceName=object.informationSourceNames.split(",");
		personName=object.inputPerSonNames.split(",");
		personId=object.inputPersonID.split(",");
		Allsourcename=object.informationSourceID.split(",");;
		AllportName=object.safetyPortId;
			var timer1=setInterval(function(){

			$("input[name='sourceCheck']").each(function(){
				for(var i=0;i<sourceName.length;i++){
					if($(this).attr("data-name")==sourceName[i]){
						$(this).attr("checked","checked");
						break;
					}
				}
				
			});
			if(sorFlag){
				clearInterval(timer1);
			}
		},1000)
		
		var timer2=setInterval(function(){
			$("input[name='safePort']").each(function(){
					if($(this).attr("data-name")==object.safetyPortNames){
						$(this).attr("checked","checked");
						
				}
				
			})
		if(fenFlag){
				clearInterval(timer2);
			}
		},1000)
		
		addSelect(".sele",object.safetyPortNames);
		addSelect(".pes",object.informationClassificationNames);
		addSelect(".sort",object.informationSortNames);
		for(var i=0;i<personName.length;i++){
			if(personName[i]!=""){
				var html="<span  class='parsbox'><span  class='glyphicon glyphicon-user' aria-hidden='true' ></span><span class='select-data-user' data-id="+personId[i]+">"+personName[i]+"</span>&nbsp;&nbsp;<span   class='glyphicon glyphicon-remove' aria-hidden='true'></span></span>"
		        $(".label1").append(html);
			}
			
		}

		$(".briefing").text(object.informationProfile);//简介
		$(".basic").text(object.standard);//标准
		$(".step").text(object.mesure);//措施
		$(".cont").text(object.informationConternt);//内容
	
		file=object.appendix;
		if(file==null||file=="[]"){
			
		}else{
			file=JSON.parse(file);
			var appendix=object.appendix.substring(1,object.appendix.length-1);
			appendix=appendix.split(",");
			YuXi.appendix.get(appendix);
		}
		cancelappend();
	},function(){

	})

}
//删除附件
	function cancelappend()
	{
		
		$(".appendixcancel span").click(function(){
			file=[];
			var dataurl=$(this).attr("data-url");
			$(this).parent(".appendixcancel").remove();
			$("#valAppendix ").find(".appendixcancel").each(function(){
				
				file.push($(this).find("span").attr("data-url"));
			})
		
		})
	}
	//向后台提交附件，返回地址
	 function fileup (){
			$("#loading").show();
			 $("#loadOk").hide();
	    $.ajaxFileUpload({
	        type:"post",
	        secureuri:false,
	        dataType:"json",      
	        url:"/yuxi/userFileUp.do",
	        fileElementId:"upfile-haoping",
	        success:function(data,status){

	        	var appendix=JSON.stringify(data.addressList);
	        	
	        	if(file==null ||file=="[]"){
	        		file=JSON.parse(appendix);
	        		
	        	}else{
	        		appendix= appendix.substring(1,appendix.length-1).split(",");
	        		for(var i=0;i<appendix.length;i++){
		        		file.push(appendix[i].substring(1,appendix[i].length-1));
		        	}
		        	
	        	}
	        	//alert();
	        	//console.log(file);
	        	$("#fileValue").remove();
	        	var html='<input id="upfile-haoping" name="files" multiple="multiple" style="position:absolute; right:0; top:0; font-size:100px; opacity:0; filter:alpha(opacity=0);" type="file" value="浏览" />';
	        	$("#fileUp").append(html);
	        	$("#loading").hide();
	        	$("#loadOk").show();
	        },
	        error:function(data){
	        	
	          
	        } 
	        
	      });
	    }


var fff={sele:true,sort:false,pes:false};
function addSelect(className,value){
	var length=className.length;
	
	var newname=className.substring(1,length);
	var time=setInterval(function(){
		if(fff.sele==true && fff.sort==true && fff.pes==true)
		{

			clearInterval(time);
		}
		if(checkFlag[newname]==true)
		{
			$(className+" option").each(function(){
			if($(this).html()==value){
				$(this).attr("selected","selected");

				if(className==".sele")
				{
					$(".select2-selection__rendered").eq(0).attr("title",value);
					$(".select2-selection__rendered").eq(0).html(value);
				}
				else if(className==".pes")
				{
					$(".select2-selection__rendered").eq(0).attr("title",value);
					$(".select2-selection__rendered").eq(0).html(value);
				}
				else
				{
					$(".select2-selection__rendered").eq(1).attr("title",value);
					$(".select2-selection__rendered").eq(1).html(value);
				}
				fff[newname]=true;
			}
			});
		}
		
	},50);
	
}


function getInformation(){
	
	var check=[];
    var sourceName=[];
    var personId=[];
    var personName=[];
    $("input[name='source']:checked").each(function () {
    	check.push($(this).val());
        sourceName.push($(this).attr("data-na"));
            
     });
    $(".select-data-user").each(function(){
    	personId.push($(this).attr("data-id"));
		personName.push($(this).html());
		
		
	})
	information.id=detailId;
	var sourceid="";
	var sourcename="";
	 $('input:checkbox[name=sourceCheck]:checked').each(function(i){
	 		sourceid=sourceid+$(this).attr("data-id")+",";
	 		sourcename=sourcename+$(this).attr("data-name")+",";
	 })
	
    information.informationSourceID=sourceid;//渠道
    information.informationSourceNames=sourcename;
    information.safetyPortId=$("input[type='radio']:checked").attr("data-id");; //分口
    information.safetyPortNames=$("input[type='radio']:checked").attr("data-name");
    information.informationClassificationId=parseInt($(".pes option:selected").val());//分级
    information.informationClassificationNames=($(".pes option:selected").html());
    information.informationSortId=($(".sort option:selected").val());//分类
    information.informationSortNames=($(".sort option:selected").html());
    information.informationProfile=$(".briefing").text();//简介
    information.mesure=$(".step").text();//措施
    information.standard=$(".basic").text();//标准
    information.informationConternt=$(".cont").text();//内容
    information.inputPersonID=personId.join(",");//参与人
    information.inputPerSonNames=personName.join(",");
  	information.appendix=JSON.stringify(file);

   if(!isNull(information.informationSourceID)){
    	myTool.alert({		
			title:"提示",
			context:"修改失败,渠道不能为空。",
			isMask:true,
			callback:function(){
				}
			});

    	YuXi.scrollbar.scroll("#resour");
    	return false;
    }
    if(!isNull(information.safetyPortId)){
    	$("#badmodal").modal('show');
    	return false;
    }
    if(!isNull(information.informationClassificationId)){
    	$("#badmodal").modal('show');
    	return false;
    }
    if(!isNull(information.informationSortId)){
    	$("#badmodal").modal('show');
    	return false;
    }
    if(!isNull(information.informationProfile)){
    	myTool.alert({		
			title:"提示",
			context:"修改失败,简介不能为空。",
			isMask:true,
			callback:function(){
				}
			});

    	YuXi.scrollbar.scroll("#brie");
    	return false;
    }
    if(!isNull(information.informationConternt)){
    	myTool.alert({		
			title:"提示",
			context:"修改失败,内容不能为空。",
			isMask:true,
			callback:function(){
				}
			});

    	YuXi.scrollbar.scroll("#content");
    	return false;
    }
    myTool.alert({		
		title:"提示",
		context:"是否确认提交修改后的信息?",
		isMask:true,
		callback:function(){
			
			requestUpdate(information);
		}
	});
    
}

/*判断输入合法性*/
function isNull(str){
	if(str==null||str==""){
		return false;
	}else{
		return true;
	}
}


function modal(msg,cont){
	myTool.alert({		
		title:msg,
		context:cont,
		isMask:true,
		callback:function(){}
	});
}

//修改分口，分类，分级，标准，措施
function requestUpdate(information)
{	var  flowName="";
	if(flowId==1){
		flowName="InfoManage";
	}
	if(flowId==2){
		flowName="FirstCheck";
	}
	if(flowId==3){
		flowName="ReCheck";
	}
	if(flowId==4){
		flowName="Check";
	}
	if(flowId==5){
		flowName="InfoResearch";
	}
	if(flowId==6){
		flowName="TaskDispatch";
	}
	if(flowId==7){
		flowName="CurTaskDispatch";
	}
	var url=flowName+"/userUpdataInformation.do";//修改的地址;
	YuXi.util.get(url,information,function(data){
		if(data.status)
		{
			myTool.alert({		
				title:"提示",
				context:"信息修改成功！",
				isMask:true,
				callback:function(){
					window.location.href="submittedInfo.jsp?menuId=2";
				}
			});
		}
		else
		{
			myTool.alert({		
				title:"提示",
				context:"信息修改失败！",
				isMask:true,
				callback:function(){}
			});
		}
	},function(){
		myTool.alert({		
			title:"提示",
			context:"信息修改失败！",
			isMask:true,
			callback:function(){}
		});
	})
}

$(document).on("click", ".info-sub-a", function() {
		//var id = $(this).attr("data-id");
		var url="SubToFirstCheck.do";
		myTool.alert({		
			title:"提示",
			context:"是否确认提交信息?",
			isMask:true,
			callback:function(){
				YuXi.util.get(url, {infoId: detailId}, function(data) {
					if(data.status){
						myTool.alert({		
							title:"提示",
							context:"提交信息成功。",
							isMask:true,
							callback:function(){
								window.location.reload();
							
							}
						});
						window.location.href="submittedInfo.jsp";
					}
				},function(){
					
				});
				
			}
		});
		
	});


//删除
$(document).on("click", ".delete", function() {	
			//deleteid = $(this).attr("id");
			myTool.alert({
				title:"删除确认",
				context:"你确定要删除此条信息吗?",
				callback:function(){
					requestDele(detailId);
				},
				isMask:true
			});
		})

//删除确认
	function requestDele(id) {
		var dataid = {
			id: id
		};
		var url = "userDelInformationById.do" //删除信息地址;
		YuXi.util.get(url, dataid, function(data) {
			//$("#" + id).parents("tr").remove();
			$("#successmodel").modal('show');
			window.location.href="submittedInfo.jsp";

		}, function() {
			$("#badmodal").modal('show');
		})
	}


})